import { prisma } from '@src/common/database'

export type WithdrawSettings = {
  rate: number
  feePercent: number
  minPoints: number
  banks?: string[]
}

const DEFAULT_WITHDRAW_SETTINGS: WithdrawSettings = {
  rate: 0.01,
  feePercent: 10,
  minPoints: 0,
  banks: [],
}

const WITHDRAW_KEY = 'withdraw.settings'

export async function getWithdrawSettings(): Promise<WithdrawSettings> {
  const rec = await prisma.appSetting.findUnique({ where: { key: WITHDRAW_KEY } })
  if (!rec?.value) return DEFAULT_WITHDRAW_SETTINGS
  try {
    const v = rec.value as any
    return {
      rate: v?.rate !== undefined ? Number(v.rate) : DEFAULT_WITHDRAW_SETTINGS.rate,
      feePercent: v?.feePercent !== undefined ? Number(v.feePercent) : DEFAULT_WITHDRAW_SETTINGS.feePercent,
      minPoints: v?.minPoints !== undefined ? Number(v.minPoints) : DEFAULT_WITHDRAW_SETTINGS.minPoints,
      banks: Array.isArray(v?.banks) ? v.banks.map(String) : DEFAULT_WITHDRAW_SETTINGS.banks,
    }
  } catch {
    return DEFAULT_WITHDRAW_SETTINGS
  }
}

export async function setWithdrawSettings(v: WithdrawSettings) {
  await prisma.appSetting.upsert({
    where: { key: WITHDRAW_KEY },
    create: { key: WITHDRAW_KEY, value: v as any },
    update: { value: v as any },
  })
}

export function calcWithdrawAmount(points: bigint, s: WithdrawSettings): { gross: number; fee: number; net: number } {
  const gross = Number(points) * s.rate
  const fee = +(gross * (s.feePercent / 100)).toFixed(2)
  const net = +(gross - fee).toFixed(2)
  return { gross: +gross.toFixed(2), fee, net }
}

